using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using T.FAS.Runtime.Action.Service;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity.ScheduleJob;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.Engine
{
    public class ActionJobEngine : IScheduleJobImpEngineProxy, IScheduleJobExecuteHandler, IScheduleJobDataResultBuilder
    {
        public void AfterExecute(ScheduleJobExecContext execContext, TResult result)
        {
        }

        public void BeforeExecute(ScheduleJobExecContext execContext)
        {
        }

        public TResult BuildScheduleJobDataResult(ScheduleJobExecContext context, object dataResult)
        {
            return new TResult();
        }

        public object Execute(ScheduleJobExecContext context)
        {
            try
            {
                var sJob = context.ScheduleJobMetaData as Metadata.Entity.ScheduleJob.ScheduleJob;

                if (sJob == null)
                    throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobMetadataNotExistError, CommonStringClassEngine.ActionJobEngine_NotValidSchedulaJobMetaData);
                if (sJob.JobType != Metadata.Entity.ScheduleJob.JobType.Action)
                    throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError, string.Format(CommonStringClassEngine.ActionJobEngine_Execute1,sJob.Code));
                if (string.IsNullOrEmpty(sJob.RelatedMetaDataID))
                    throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError, string.Format(CommonStringClassEngine.ActionJobEngine_Execute2,sJob.Code));
                var parameters = context.Instance.Data.GetDictionary();
                List<ActionParameter> parameterList = new List<ActionParameter>();
                if (parameters != null && parameters.Count > 0)
                {
                    int order = 0;
                    parameters.Keys.ToList().ForEach(x=>
                    {
                        parameterList.Add(new ActionParameter()
                        {
                            Order = order,
                            ParameterName = x,
                            ParameterValue = parameters[x]
                        });
                        order++;
                    });
                }
                var result = ActionExecuteService.GetInstance.Execute(context.ScheduleJobMetaData.RelatedMetaDataID, ActionType.Action, parameterList);
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ExecuteError(ScheduleJobExecContext execContext, Exception exception)
        {
        }
    }
}
